from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

import db
import base64
from news import news
from config import *
class newscontroller(object):
	lookup = None
	def __init__(self, lup ):
		self.lookup = lup

	def index(self, msg=None):
		sess = db.getsession()
		n = sess.query(news).all()
		return self.lookup.get_template("news.html").render(news=n, msg=msg)
	index.exposed = True

	def editnews(self, newsid=None):
		sess = db.getsession()
		if newsid:
			n = sess.query(news).filter(news.NEWSID == newsid).one()
		else:
			n = news()
		return self.lookup.get_template("editnews.html").render(n = n, table=db.news_table)
	editnews.exposed = True

	def savenews(self, **kwargs):
		sess = db.getsession()
		try:
			n = sess.query(news).filter(news.NEWSID == kwargs['NEWSID']).one()
		except:
			n = news()
			sess.save(n)

		for k in kwargs:
			if kwargs[k]:
				setattr(n, k, kwargs[k])
		n.NEWSDATE = parsedate(n.NEWSDATE)
		try:
			sess.flush()
			msg = "News Item " + n.TITLE + " has been saved."
		except Exception, e:
			msg = "Failed to Save News Item "+ str(e)
		return self.index(msg=msg)
	savenews.exposed = True

	def deletenews(self, newsid):
		sess = db.getsession()
		try:
			n = sess.query(news).filter(news.NEWSID == newsid).one()
			sess.delete(n)
			return self.index(msg="Successfully Deleted")
		except:
			return self.index(msg="Failed to delete")
	deletenews.exposed = True	
